package org.lc.oauth.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lc.platform.base.domain.JwtUser;
import org.lc.platform.base.enums.AuthResultEnum;
import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtValidationException;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtUtil {


    private final JwtDecoder jwtDecoder;

    public JwtUser getJwtUser(String token) throws BadJwtException {
        try {
            Jwt jwt = jwtDecoder.decode(token);
            var claims = jwt.getClaims();
            if (ObjUtil.isNotNull(claims)) {
                var user = new JwtUser();
                BeanUtil.copyProperties(claims, user, false);
                return user;
            }
        } catch (Exception e) {
            if (Objects.equals(e.getClass(), JwtValidationException.class)) {
                OAuth2EndpointUtils.throwError(AuthResultEnum.EXP_TOKEN);
            } else {
                OAuth2EndpointUtils.throwError(AuthResultEnum.INVALID_TOKEN);
            }
        }
        return new JwtUser();
    }
}
